/*
 * Copyright (c) 2008, Russell Garrett
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.moneydance.modules.features.portfolioallocation;

import com.moneydance.awt.*;
import com.moneydance.apps.md.model.*;
import java.util.*;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import javax.swing.border.*;
import javax.swing.table.AbstractTableModel;

@SuppressWarnings("serial")
public class AccountListWindow extends JFrame implements ActionListener {
	private Main extension;
	private JTable securitiesList;
	private JButton closeButton;
	private JComboBox comboBox;

	public AccountListWindow(Main extension) {
		super("Portfolio Allocation");
		this.extension = extension;

		RootAccount root = extension.getUnprotectedContext().getRootAccount();
		securitiesList = new JTable(new SecuritiesTableModel(root));

		comboBox = new JComboBox();
		comboBox.setEditable(true);
		updateComboBox();
		securitiesList.getColumnModel().getColumn(1).setCellEditor(
				new DefaultCellEditor(comboBox));

		closeButton = new JButton("Close");

		JPanel p = new JPanel(new GridBagLayout());
		p.setBorder(new EmptyBorder(10, 10, 10, 10));
		p.add(new JScrollPane(securitiesList), AwtUtil.getConstraints(0, 0, 1,
				1, 4, 1, true, true));
		p.add(Box.createVerticalStrut(8), AwtUtil.getConstraints(0, 2, 0, 0, 1,
				1, false, false));
		// p.add(clearButton, AwtUtil
		// .getConstraints(0, 3, 1, 0, 1, 1, false, true));
		p.add(closeButton, AwtUtil
				.getConstraints(1, 3, 1, 0, 1, 1, false, true));
		getContentPane().add(p);

		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		enableEvents(WindowEvent.WINDOW_CLOSING);
		closeButton.addActionListener(this);
		setSize(500, 400);
		AwtUtil.centerWindow(this);
	}

	private void updateComboBox() {
		comboBox.removeAllItems();
		for (String c : ClassifiedSecurity.getClasses()) {
			comboBox.addItem(c);
		}
	}

	@SuppressWarnings("serial")
	class SecuritiesTableModel extends AbstractTableModel {
		ArrayList<ClassifiedSecurity> securities;

		String[] columnNames = { "Security", "Classification" };

		@SuppressWarnings("unchecked")
		public SecuritiesTableModel(RootAccount root) {
			securities = ClassifiedSecurity.getAll(root);
			Collections.sort(securities);
		}

		public int getColumnCount() {
			return 2;
		}

		public int getRowCount() {
			return securities.size();
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {
			if (col == 0) {
				return securities.get(row).toString();
			} else if (col == 1) {
				return securities.get(row).getAssetClass();
			}
			return null;
		}

		public boolean isCellEditable(int rowIndex, int columnIndex) {
			return (columnIndex == 1);
		}

		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			if (aValue.toString().trim().equals(""))
				return;
			securities.get(rowIndex).setAssetClass(aValue.toString());
			updateComboBox();
		}
	}

	public static void addSubAccounts(Account parentAcct, StringBuffer acctStr) {
		int sz = parentAcct.getSubAccountCount();
		for (int i = 0; i < sz; i++) {
			Account acct = parentAcct.getSubAccount(i);
			if (acct instanceof SecurityAccount) {
				acctStr.append(acct.getAccountName());
				acctStr.append("\n");
			}
			addSubAccounts(acct, acctStr);
		}
	}

	public void actionPerformed(ActionEvent evt) {
		Object src = evt.getSource();
		if (src == closeButton) {
			extension.closeConsole();
		}
	}

	public final void processEvent(AWTEvent evt) {
		if (evt.getID() == WindowEvent.WINDOW_CLOSING) {
			extension.closeConsole();
			return;
		}
		if (evt.getID() == WindowEvent.WINDOW_OPENED) {
		}
		super.processEvent(evt);
	}

	void goAway() {
		setVisible(false);
		dispose();
		extension.getHomePageView().refresh();
	}
}
